<template>
    <div class="app-container">
        <el-row :gutter="10">
            <!-- 左侧卡片 -->
            <el-col :span="12">
                <el-card shadow="hover" class="full-height">
                    <!-- 按钮组 -->
                    <el-button-group class="mb15">
                        <el-button type="primary" icon="Plus" @click="handleApply">申请</el-button>
                        <el-button type="success" icon="Edit" @click="handleUpdateApply">申请更新</el-button>
                        <el-button type="warning" icon="DocumentChecked" @click="handleReview">审核</el-button>
                    </el-button-group>

                    <!-- 查询表单 -->
                    <el-row :gutter="10" class="mb10">
                        <el-col :span="24">
                            <el-form :model="queryParams" ref="queryRef" label-width="50px" label-position="left">
                                <el-row :gutter="8">
                                    <el-col :span="8">
                                        <el-form-item label="名称">
                                            <el-input v-model="queryParams.name" placeholder="请输入名称" clearable
                                                @keyup.enter="handleQuery" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="2.5">
                                        <el-button type="primary" icon="Search" @click="handleQuery"
                                            style="width: 100%">搜索</el-button>
                                    </el-col>
                                    <el-col :span="2.5">
                                        <el-button icon="Refresh" @click="resetQuery" style="width: 100%">重置</el-button>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </el-col>
                    </el-row>

                    <!-- 数据表格 -->
                    <el-table :data="tableData" border @row-click="handleRowClick">
                        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
                        <el-table-column prop="name" label="名称" width="150" align="center"></el-table-column>
                        <el-table-column prop="topicName" label="主题名称" width="180" align="center"></el-table-column>
                        <el-table-column prop="statusTxt" label="状态" align="center"></el-table-column>
                    </el-table>

                    <!-- 分页 -->
                    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                        v-model:limit="queryParams.pageSize" @pagination="getList" />
                </el-card>
            </el-col>

            <!-- 右侧卡片 -->
            <el-col :span="12">
                <el-card shadow="hover" class="full-height">
                    <div v-if="selectedItem">
                        <!-- 详情信息 -->
                        <el-descriptions title="数据源详情" :column="1" border style="margin-bottom: 20px;">
                            <el-descriptions-item label="名称">{{ selectedItem.name }}</el-descriptions-item>
                            <el-descriptions-item label="主题名称">{{ selectedItem.topicName }}</el-descriptions-item>
                            <el-descriptions-item label="数据提取说明">{{ selectedItem.description || '无'
                                }}</el-descriptions-item>
                        </el-descriptions>

                        <!-- 字段查询表单 -->
                        <el-row :gutter="10" class="mb10">
                            <el-col :span="24">
                                <el-form :model="queryParams" ref="queryRef" label-width="50px" label-position="left">
                                    <el-row :gutter="10">
                                        <el-col :span="8">
                                            <el-form-item label="字段">
                                                <el-input v-model="fieldQueryParams.field" placeholder="请输入字段名"
                                                    clearable @keyup.enter="handleQuery" />
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="2.5">
                                            <el-button type="primary" icon="Search"
                                                @click="handleFieldQuery">搜索</el-button>
                                        </el-col>
                                        <el-col :span="2.5">
                                            <el-button icon="Refresh" @click="resetFieldQuery">重置</el-button>
                                        </el-col>
                                    </el-row>
                                </el-form>
                            </el-col>
                        </el-row>

                        <!-- 字段表格 -->
                        <el-table :data="fieldTableData" border height="400px" style="width: 100%;">
                            <el-table-column prop="field" label="字段" width="120" align="center"></el-table-column>
                            <el-table-column prop="type" label="类型" width="100" align="center"></el-table-column>
                            <el-table-column prop="description" label="描述" align="center"></el-table-column>
                            <el-table-column prop="nullable" label="是否允许空" width="110" align="center">
                                <template #default="{ row }">
                                    {{ row.nullable ? '是' : '否' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="primaryKey" label="是否主键" width="110" align="center">
                                <template #default="{ row }">
                                    {{ row.primaryKey ? '是' : '否' }}
                                </template>
                            </el-table-column>
                            
                        </el-table>

                        <!-- JSON 示例展示 -->
                        <div style="margin-top: 20px;">
                            <h4>JSON 数据样例</h4>
                            <el-input v-model="jsonSample" type="textarea" :rows="6" readonly />
                        </div>
                    </div>
                    <div v-else class="no-selection">
                        请选择左侧条目以查看详情
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 申请弹窗 -->
        <el-dialog title="申请数据" v-model="applyDialogVisible" width="45%" :close-on-click-modal="false">
            <el-form ref="applyFormRef" label-width="100px" :model="applyForm" :rules="applyRules">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="申请名" prop="applyName">
                            <el-input v-model="applyForm.applyName" placeholder="请输入申请名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="简称" prop="shortName">
                            <el-input v-model="applyForm.shortName" placeholder="请输入简称" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="数据提取说明" prop="description">
                            <el-input v-model="applyForm.description" type="textarea" :rows="3"
                                placeholder="请输入数据提取说明" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 字段列表 -->
                <el-row :gutter="20">
                    <el-col :span="24">
                        <div
                            style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                            <h4>字段信息</h4>
                            <div>
                                <el-button icon="Plus" @click="addField">新增行</el-button>
                                <el-button icon="Delete" type="danger" @click="deleteSelectedFields">删除选中行</el-button>
                            </div>
                        </div>
                        <el-table :data="applyForm.fields" @selection-change="handleSelectionChange" border
                            style="width: 100%; height: 400px;">
                            <el-table-column type="selection" width="50" align="center"></el-table-column>
                            <el-table-column label="字段名称" align="center">
                                <template #default="{ row }">
                                    <el-input v-model="row.fieldName" placeholder="字段名称" />
                                </template>
                            </el-table-column>
                            <el-table-column label="字段类型" align="center">
                                <template #default="{ row }">
                                    <el-select v-model="row.fieldType" placeholder="请选择类型" style="width: 100%">
                                        <el-option v-for="item in fieldTypes" :key="item.value" :label="item.label"
                                            :value="item.value"></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="是否主键" align="center" width="100">
                                <template #default="{ row }">
                                    <el-checkbox v-model="row.primaryKey"></el-checkbox>
                                </template>
                            </el-table-column>
                            <el-table-column label="允许空" align="center" width="100">
                                <template #default="{ row }">
                                    <el-checkbox v-model="row.nullable"></el-checkbox>
                                </template>
                            </el-table-column>
                            <el-table-column label="字段说明" align="center">
                                <template #default="{ row }">
                                    <el-input v-model="row.comment" placeholder="字段说明" />
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="applyDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitApplyForm">提 交</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="DataSourceLayout">
import { ref, reactive } from 'vue'

const { proxy } = getCurrentInstance()

const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    name: ''
})

const fieldQueryParams = reactive({
    field: ''
})

const tableData = ref([
    {
        id: 1,
        name: "数据源A",
        topicName: "主题1",
        statusTxt: "已启用"
    },
    {
        id: 2,
        name: "数据源B",
        topicName: "主题2",
        statusTxt: "待审核"
    }
])

const fieldTableData = ref([
    {
        field: "id",
        type: "int",
        description: "主键",
        nullable: false,
        primaryKey: true
    },
    {
        field: "name",
        type: "varchar",
        description: "名称",
        nullable: false,
        primaryKey: false
    }
])

const total = ref(tableData.value.length)
const selectedItem = ref(null)
const jsonSample = ref('{"id": 1, "name": "示例"}')

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.pageNum = 1
}

/** 重置按钮操作 */
function resetQuery() {
    queryParams.name = ''
    handleQuery()
}

/** 点击行触发 */
function handleRowClick(row) {
    selectedItem.value = row
    jsonSample.value = JSON.stringify({ id: row.id, name: row.name }, null, 2)
}

/** 搜索字段 */
function handleFieldQuery() { }

/** 重置字段搜索 */
function resetFieldQuery() {
    fieldQueryParams.field = ''
    handleFieldQuery()
}

/** 申请按钮点击事件 */
function handleApply() {
    applyDialogVisible.value = true
}

function handleUpdateApply() {
    alert('申请更新按钮被点击')
}

function handleReview() {
    alert('审核按钮被点击')
}

const applyDialogVisible = ref(false)

const applyForm = reactive({
    applyName: '',
    shortName: '',
    description: '',
    fields: []
})

const fieldTypes = [
    { label: '整型', value: 'int' },
    { label: '长整型', value: 'bigint' },
    { label: '字符型', value: 'varchar' },
    { label: '日期时间', value: 'datetime' },
    { label: '布尔值', value: 'boolean' },
    { label: '浮点数', value: 'float' }
]

const applyRules = reactive({
    applyName: [{ required: true, message: '申请名不能为空', trigger: 'blur' }],
    shortName: [{ required: true, message: '简称不能为空', trigger: 'blur' }]
})

/** 新增字段行 */
function addField() {
    applyForm.fields.push({
        fieldName: '',
        fieldType: '',
        primaryKey: false,
        nullable: true,
        comment: ''
    })
}

const selectedRows = ref([])
function handleSelectionChange(rows) {
    selectedRows.value = rows;
}

/** 删除选中字段行 */
function deleteSelectedFields() {

    // const selected = applyForm.fields.filter(row => !row._checked)
    // applyForm.fields = selected


    if (selectedRows.value.length === 0) {
        proxy.$modal.msgError("请先选择要删除的字段行")
        return
    }

    // 过滤掉选中的行
    applyForm.fields = applyForm.fields.filter(item => {
        return !selectedRows.value.some(sel => sel === item);
    });

    // 清空选中状态
    this.selectedRows = [];
    this.$message.success('删除成功');
}

/** 提交 */
function submitApplyForm() {
  let valid = true

  // 清除所有错误状态
  applyForm.fields.forEach(row => {
    row._error = false
  })

  const nameMap = {}

  for (const row of applyForm.fields) {
    const name = row.fieldName?.trim()
    if (!name) continue

    if (nameMap[name]) {
      valid = false
    } else {
      nameMap[name] = row
    }
  }

  if (!valid) {
    proxy.$modal.msgError("存在重复的字段名，请修正后再提交")
    return
  }

  // 表单通过验证，继续提交逻辑
  proxy.$refs['applyFormRef'].validate(validForm => {
    if (validForm) {
      console.log('提交的申请数据:', unref(applyForm))
      proxy.$modal.msgSuccess("申请成功")
      applyDialogVisible.value = false
    }
  })
}





</script>

<style scoped>
.full-height {
    height: calc(100vh - 30px);
    overflow: hidden;
    margin-top: 5px;
}

.card-style {
    display: flex;
    flex-direction: column;
}

.mb10 {
    margin-bottom: 10px;
}

.mb15 {
    margin-bottom: 15px;
}

.no-selection {
    text-align: center;
    padding-top: 100px;
    color: #999;
    font-size: 24px;
    font-weight: bold;
    letter-spacing: 3px;
}

:deep(.el-card__body) {
    flex: 1;
    display: flex;
    flex-direction: column;
}

:deep(.el-form-item__content) {
    width: 100%;
}

.dialog-footer {
    text-align: right;
}
</style>